//
//  FaastManager.swift
//  FastV
//
//  Created by DC on 2024/6/25.
//

import Foundation

// MARK: -- 文件处理模型
class YYGTaskManager: NSObject {
    static let shared = YYGTaskManager()
    private override init() {}
    
    //类型
    private let YYG_TaskFile = "YYGTask"
    
    //获取路径
    private func getPath(path: String)-> String {
        var filepath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
        filepath+="/\(YYG_TaskFile).plist"
        return filepath
    }
    
    //存储数据
    private func saveArray(path: String, _ data: [[String: Any]]){
             let filePath = getPath(path: path)
             NSKeyedArchiver.archiveRootObject(data, toFile: filePath)
        }
   //  获取数据
    private func getAarray(path: String)->[[String: Any]]{
        let filePath = getPath(path: path)
        guard var array = NSKeyedUnarchiver.unarchiveObject(withFile: filePath) as? [[String: Any]] else{
            return []
        }
        return array
    }
    // MARK: -- 添加下载产品数据
    func addTask(task: TaskModel){
        guard let dic = task.toJSON() else {
            return
        }
        var array = getAarray(path: YYG_TaskFile)
        array.append(dic)
        saveArray(path: YYG_TaskFile, array)
    }
    
    // MARK: -- 返回数据
    func getTasks()->[TaskModel]{
        
        let array = getAarray(path: YYG_TaskFile)
        guard let lists = JSONDeserializer<TaskModel>.deserializeModelArrayFrom(array: array) as? [TaskModel] else {
            return []
        }
        return lists
    }
    
    // MARK: -- 移除产品数据
    func removeTask(task: TaskModel){
        
        let array = getAarray(path: YYG_TaskFile)
        let arr = array.filter { dic in
            return !(dic.strValue("id") == task.id)
        }
        saveArray(path: YYG_TaskFile, arr)
    }
    
    // MARK: -- 移除所有产品
    func removeAll(){
        saveArray(path: YYG_TaskFile, [])
    }
    
    // MARK: -- 移除沙盒中有些话的具体文件
    func removeItem(fileName: String){
        
        var filePath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
        filePath += "/Files/\(fileName)"
        try? FileManager.default.removeItem(atPath: filePath)
    }
   
}
